import axios from 'axios';
import errHandle from './errHandle';

const instance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'x-csrf-token': window.INIT_STATE.common.csrfToken,
    'Content-Type': 'application/json; charset=utf-8',
    Accept: 'application/json',
  },
  transformResponse: [(data) => {
    try {
      return JSON.parse(data);
    } catch (err) {
      return data;
    }
  }],
  withCredentials: true,
});
export default ({
  get(...args) {
    return instance.get(...args)
      .then(res => res.data)
      .then((data) => {
        if (data.code === 0) {
          return data;
        }
        errHandle(data);
        const err = new Error();
        err.code = data.code;
        err.msg = data.msg;
        err.data = data.data;
        throw err;
      });
  },
  post(...args) {
    return instance.post(...args)
      .then(res => res.data)
      .then((data) => {
        if (data.code === 0) {
          return data;
        }
        errHandle(data);
        throw data;
      });
  },
});
